import React, {useCallback} from 'react';
import {Select, Button, Card, Dialog, Field, Icon, List, Message, Pagination, Table} from '@alifd/next';
import {useFusionTable, useSetState} from 'ahooks';

import {request} from 'ice';
import {datetimeStamp2String} from '@/utils/locale';
import EmptyBlock from './EmptyBlock';
import ExceptionBlock from './ExceptionBlock';
import DialogOperation from './DialogOperation';
import {ActionType, OperaitionProps} from './Operation';

import styles from './index.module.scss';


interface ColumnWidth {
  name: number;
  email: number;
  phone: number;
  gender: number;
  operation: number;
}

interface DialogState {
  columnWidth: ColumnWidth;
  optCol: any;
  actionType: ActionType;
  actionVisible: boolean;
}

const defaultColumnWidth: ColumnWidth = {
  name: 140,
  email: 500,
  phone: 500,
  gender: 140,
  operation: 150,
};

const DialogTable: React.FC = () => {


  // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
  // @ts-ignore
  const [type, setQueryType] = useSetState<string>('0');
  const Option = Select.Option;

  const getTableData = (
    {current, pageSize}: { current: number; pageSize: number },
    formData: { status: 'normal' | 'empty' | 'exception' }
  ): Promise<any> => {
    console.log(type);
    if (!formData.status || formData.status === 'normal') {
      const data = request({
        url: `/v1/balance/Commodity/${type[0]}`,
        method: 'get',
      });
      return data.then(res => {
        return {
          list: res.data,
        }
      })
    }
    if (formData.status === 'empty') {
      return Promise.resolve([]);
    }
    if (formData.status === 'exception') {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          reject(new Error('data exception'));
        }, 1000);
      });
    }

    return Promise.resolve([]);
  };


  const [state, setState] = useSetState<DialogState>({
    columnWidth: defaultColumnWidth,
    optCol: null,
    actionType: 'preview',
    actionVisible: false,
  });
  const {actionVisible, columnWidth, optCol} = state;
  const field = Field.useField([]);
  const {paginationProps, tableProps, search, error, refresh} = useFusionTable(getTableData, {
    field,
  });

  const {reset} = search;

  const onResizeChange = (dataIndex: keyof typeof defaultColumnWidth, width: number) => {
    const newWidth = {
      ...columnWidth,
    };
    newWidth[dataIndex] += width;
    setState({columnWidth: newWidth});
  };

  const operationCallback = useCallback(({actionType, dataSource}: OperaitionProps): void => {
    setState({
      actionType,
      optCol: dataSource,
      actionVisible: true,
    });
  }, [setState]);

  const handleCancel = useCallback((): void => {
    setState({actionVisible: false});
  }, [setState]);

  const handleOk = useCallback((): void => {
    const {actionType, optCol} = state;
    if (actionType === 'preview') {
      handleCancel();
      return;
    }
    Message.success(actionType === 'add' ? '添加成功!' : '编辑成功!');
    reset();
    handleCancel();
  }, [handleCancel, reset, state]);

  const handleDelete = useCallback((data: any) => {
    if (!data) {
      return;
    }
    const id = data.id
    Dialog.confirm({
      title: '删除提醒',
      content: `确定删除 ${data.name} 吗`,
      async onOk() {
        const data = await request({
          // eslint-disable-next-line no-use-before-define,@typescript-eslint/ban-ts-ignore
          // @ts-ignore
          url: `/v1/balance/Commodity/${id}`,
          method: 'DELETE',
        });
        if (data.statusCode && data.statusCode === 200) {
          Message.success('删除成功!');
          reset();
        }
      }
    });
  }, [reset]);

  const cellOperation = (...args: any[]): React.ReactNode => {
    const record = args[2];
    return (
      <div>
        <Button
          text
          type="primary"
          onClick={() => operationCallback({actionType: 'edit', dataSource: record})}
        >
          编辑
        </Button>
        &nbsp;&nbsp;
        <Button
          text
          type="primary"
          onClick={() => handleDelete(record)}
        >
          删除
        </Button>
        {/*        &nbsp;&nbsp;
        <Button
          text
          type="primary"
          onClick={() => operationCallback({ actionType: 'preview', dataSource: record })}
        >
          查看
        </Button> */}
      </div>
    );
  };
  const castGmtCreat = (...args: any[]) => {
    const arg = args[0];
    if (arg) {
      return datetimeStamp2String(arg);
    } else {
      return '';
    }
  }
  const castWalletType = (...args: any[]) => {
    const arg = args[0];
    return arg === 0 ? '普通钱包' : '打工钱包';
  }
  const castBoolean = (...args: any[]) => {
    const arg = args[0];
    if (arg != null) {
      return arg ? '是' : '否';
    } else {
      return '';
    }
  }
  const onChange = function (value) {
    if (value) {
      setQueryType(value);
    } else {
      setQueryType('0');
    }
    reset();
  };

  return (
    <div className={styles.DialogTable}>
      <List>
        <List.Item>
          <div>
            <Button
              type="primary"
              onClick={() => operationCallback({actionType: 'add', dataSource: {}})}
            >
              <Icon type="add"/>
              新增
            </Button>
          </div>
        </List.Item>
        <List.Item>
          {/* eslint-disable-next-line react/jsx-no-bind */}
          <Select onChange={onChange} placeholder="0" defaultValue="0" showSearch>
            <Option value="0">普通钱包</Option>
            <Option value="1">打工钱包</Option>
          </Select>
        </List.Item>

      </List>

      <Card free>
        <Card.Content>
          <Table
            {...tableProps}
            onResizeChange={onResizeChange}
            emptyContent={error ? <ExceptionBlock onRefresh={refresh}/> : <EmptyBlock/>}
            primaryKey="email"
          >
            <Table.Column title="id" dataIndex="id" resizable width={columnWidth.email}/>
            <Table.Column title="名称" dataIndex="name" resizable width={columnWidth.phone}/>
            <Table.Column title="兑换价格(厘)" dataIndex="price" resizable width={columnWidth.name}/>
            <Table.Column title="创建时间" dataIndex="gmtCreat" cell={castGmtCreat} resizable width={columnWidth.email}/>
            <Table.Column title="最后修改时间" dataIndex="gmtModified" cell={castGmtCreat} resizable
                          width={columnWidth.phone}/>
            <Table.Column title="钱包类型" dataIndex="type" cell={castWalletType} resizable width={columnWidth.gender}/>
            <Table.Column title="操作" resizable width={columnWidth.operation} cell={cellOperation}/>
          </Table>
        </Card.Content>
      </Card>
      <DialogOperation
        visible={actionVisible}
        actionType={state.actionType}
        dataSource={optCol}
        onOk={handleOk}
        onClose={handleCancel}
        onCancel={handleCancel}
      />
    </div>
  );
}

export default DialogTable;
